package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.pipeline.Filter;
import com.example.universitylibraryback.pipeline.ReaderRegistrationContext;
import java.util.concurrent.BlockingQueue;

/**
 * 持久化过滤器
 * 负责模拟将读者信息保存到数据库
 */
public class PersistenceFilter implements Filter<ReaderRegistrationContext>, Runnable {
    private BlockingQueue<ReaderRegistrationContext> inputQueue;
    private BlockingQueue<ReaderRegistrationContext> outputQueue;

    // 模拟持久化服务
    private static class PersistenceService {
        public boolean saveReader(String readerId, String readerName, String email) {
            // 模拟数据库保存操作
            System.out.printf("Saving reader to database: ID=%s, Name=%s, Email=%s\n", 
                             readerId, readerName, email);
            return true; // 假设保存总是成功的
        }
    }

    private final PersistenceService persistenceService = new PersistenceService();

    @Override
    public void process(BlockingQueue<ReaderRegistrationContext> inputQueue,
                        BlockingQueue<ReaderRegistrationContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                ReaderRegistrationContext context = inputQueue.take();
                if (!context.isValid()) {
                    System.out.println("Skipping persistence for invalid data: " + context.getMessage());
                    outputQueue.put(context);
                    continue;
                }
                
                boolean saved = persistenceService.saveReader(
                    context.getReaderId(), 
                    context.getReaderName(), 
                    context.getEmail()
                );
                
                if (saved) {
                    context.setMessage(context.getMessage() + ". Reader registered successfully.");
                } else {
                    context.setValid(false);
                    context.setMessage("Failed to save reader information.");
                }
                
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("PersistenceFilter interrupted.");
        }
    }
}